/**
 * @date: 2025/3/22
 * @fileName: ImChat
 * @Description: 聊天
 */
import { acceptHMRUpdate, defineStore } from 'pinia';
import { useAuthStore } from '@/stores/modules/auth';
import { useUserStore } from '@/stores/modules/user';
const { wsCache } = useCache();
const message = useMessage();
import * as ApiMsg from '@/api/im';
import * as ApiCommon from '@/api/common';
import { IM_CONNECT } from '@/enums/appEnum';
import { ImCountEnum } from '@/enums/imEnum';
import type { chatListEntity } from '@/entity/im/ImEntity';
import type { UserInfoEntity } from '@/entity/UserEntity';
interface ImChatStore {
	imStore: {
		userList: UserInfoEntity[];
		chatList: chatListEntity[];
	};
	imCount: {
		unRead: number;
		mention: number;
		create: number;
		join: number;
	}
	chatType: number[];
	websocket: any;
	websocketUrl: any;
	websocketMsg: any;
	isConnected: boolean;
	pingTime: number;
	reconnectAttempts: number;
}

export const useWebsocketStore = defineStore('app-websocket', {
	state: (): ImChatStore => ({
		imStore: {
			userList: [], // 用户列表
			chatList: [], // 左侧会话列表
		},
		imCount: {
			unRead: 0, // 未读
			mention: 0, // @我
			create: 0, // 创建
			join: 0, // 参与
		},
		chatType: [20, 21, 31, 32, 33], // 提示消息(群聊列表里不展示名称， 群聊消息里在中间展示)
		websocket: null,
		websocketUrl: null,
		websocketMsg: null,
		isConnected: false, //连接标识 避免重复连接
		pingTime: 30000, // 30秒发送一次ping
		reconnectAttempts: 0, // 重连次数

	}),
	actions: {
		// 用户列表
		async getUserList() {
			try {
				const res = await ApiCommon.ApiUserList();
				(this as any).imStore.userList = res || [];
			} catch (err) {
				this.imStore.userList = [];
				console.log(err);
			}
		},
		// 消息列表
		async getChatList() {
			try {
				const res = await ApiMsg.ApiChatList();
				if (res && res.length > 0) {
					this.imStore.chatList =res.map((item: any) => {
						item.topicId = item.id;
						item.lastMsg.content = item.lastMsg?.content?.replace(/<p>/g, '')?.replace(/<\/p>/g, ' ')?.replace(/\s+/g, ' ');
						item.sendName = (this as any).imStore.userList?.find((child: { id: any }) => child.id === item.lastMsg?.sendId)?.nickname;
						item.chatType = 'chat';
						if (item.messageType === 'SYSTEM_MESSAGE') {
							item.chatType = 'app';
							item.isEmpty = false;
						}
						if (item.lastMsg?.content?.includes('<img')) {
							item.lastMsg.content = item.lastMsg.content.replace(/<img.*?>/g, '[图片]');
						}
						item.lastMsg.content = item.lastMsg?.content?.replace(/<[^>]*>/g, ' ');
						return item;
					}) || [];
					this.setImCountAll();
					window.dispatchEvent(new Event('storage')); // 修改 storage 时手动触发
				}
			} catch (err) {
				this.imStore.chatList = [];
				console.log(err);
			}
		},
		// 设置消息数量
		setImCount(data: ImCountEnum){
			if(data === ImCountEnum.UnRead){
				this.imCount.unRead = this.imStore.chatList.map(item => { return item.unread })?.reduce((pre: number, next: any) => pre + next, 0);
			}else if(data === ImCountEnum.Mention){
				this.imCount.mention = this.imStore.chatList.filter(item => item.hasMentioned)?.length;
			}else if(data === ImCountEnum.Create){
				this.imCount.create = this.imStore.chatList.filter(item => item.messageType === 'GROUP_MESSAGE' && item.creatorId === useUserStore().userInfo?.id && item.unread > 0)?.length;
			}else if(data === ImCountEnum.Join){
				this.imCount.join = this.imStore.chatList.filter(item => item.messageType === 'GROUP_MESSAGE' && item.creatorId !== useUserStore().userInfo?.id && item.unread > 0)?.length;
			}
		},
		setImCountAll(){
			this.setImCount(ImCountEnum.UnRead);
			this.setImCount(ImCountEnum.Mention);
			this.setImCount(ImCountEnum.Create);
			this.setImCount(ImCountEnum.Join);
		},
		// 绑定登录人
		async handleBindUser() {
			try {
				await ApiMsg.ApiChatBind();
				// console.log('已绑定登录人===');
			} catch (err) {
				console.log(err);
			}
		},
		// 设置imStore
		setChatList(data: any) {
			this.imStore.chatList = data;
			window.dispatchEvent(new Event('storage')); // 修改 storage 时手动触发
		},
		resetChatUnRead(topicId: number) {
			this.imStore.chatList.map(item => {
				return item.unread = item.id === topicId ? 0 : item.unread;
			})
		},
		// 发送浏览器消息提醒
		sendNotification(body: any) {
			// granted已授权   denied拒绝授权
			if (Notification.permission === 'granted' && document.visibilityState === 'hidden') {
				new Notification('您有一条新的消息', {
					body,
					icon: 'http://192.168.10.200:18080/admin-api/oss/file/preview/67aaef2d46a4f090fc311391.ico', // 替换为实际的图标 URL
				});
			} else {
				// console.log('没有通知权限或浏览器不支持通知功能');
			}
		},
		// 重置重连次数
		resetConnectCount() {
			this.reconnectAttempts = 0;
		},
		// 重连websocket
		reConnectWebSocket() {
			console.log('尝试重新连接');
			if (this.reconnectAttempts >= 2) {
				console.log('已达最大重连次数', this.reconnectAttempts);
				//如果已经连上就不在重连了
				return;
			}
			this.reconnectAttempts++;
			const timer = setTimeout(() => {
				clearTimeout(timer);
				(this as any).connectWebSocket();
			}, 5000); // 延迟5秒重连，避免过多次过频繁请求重连
		},
		// 关闭websocket
		closeWebsocket() {
			if (this.websocket) {
				this.websocket.close();
				this.websocket = null;
				this.websocketUrl = null;
				this.isConnected = false;
			}
		},
		// 开启心跳
		heartStart() {
			if (this.isConnected && this.websocket) {
				this.websocket.send('ping');
				// console.log('发送ping');
			}
		},
		// 重置心跳
		heartReset() {
			const timer = setTimeout(() => {
				clearTimeout(timer);
				(this as any).heartStart();
			}, this.pingTime);
		},
		// 连接websocket
		connectWebSocket() {
			// 如果已经连接则不往下走
			// if (this.isConnected) {
			// 	return;
			// }
			const ws = new WebSocket(`${IM_CONNECT}?token=${useAuthStore().accessToken}&tenantId=${useUserStore().tenant?.id}`);
			ws.onopen = () => {
				console.log('WebSocket已连接===main');
				this.reconnectAttempts = 0; // 重置计数器
				this.isConnected = true;
				(this as any).heartStart();
				(this as any).handleBindUser(); // 登录人
			};
			ws.onmessage = async (event) => {
				if (event?.data === 'pong') {
					// console.log(`收到pong---${getCurrentDate()}`);
					(this as any).heartReset();
					return;
				}
				const eventInfo = JSON.parse(event.data);
				// 账号被顶线下
				if (eventInfo.type === 50) {
					await message.msgConfirm(eventInfo.content, false);
					return useAuthStore().logout(false);
				}
				const chat: any = JSON.parse(JSON.stringify(this.imStore.chatList));
				const { sendId, topicId, content, sendTime, mentionedIds } = eventInfo.content;
				const sendName = this.imStore.userList.find((child: { id: any }) => child.id === sendId)?.nickname;
				console.log('收到消息store====main', JSON.parse(event.data).content);
				let items = this.imStore.chatList.find((item: { topicId: any }) => item.topicId === topicId);
				const itemsIndex = this.imStore.chatList.findIndex((item: { topicId: any }) => item.topicId === topicId);
				const isMyself = useUserStore().userInfo?.id === sendId;
				// console.log('items===', isMyself, {...items});
				if (items) {
					items = {
						...items,
						sendTime,
						sendName,
						unread: isMyself ? 0 : (items?.unread || 0) + 1,
						hasMentioned: isMyself ? false : items.hasMentioned || mentionedIds?.length > 0,
					};
					items.lastMsg.content = content?.replace(/<img.*?>/g, '[图片]').replace(/<[^>]*>/g, ' ');
					chat.splice(itemsIndex, 1);
					chat.unshift(items);
					this.imStore.chatList = chat;
				}
				wsCache.set('websocketMsg', { ...JSON.parse(event.data).content, sendType: JSON.parse(event.data).type, sendName });
				window.dispatchEvent(new Event('storage')); // 修改 storage 时手动触发
				wsCache.delete('websocketMsg');
				this.setImCountAll();
			};
			ws.onclose = (event) => {
				console.log(`WebSocket已关闭${new Date()}`, event);
				this.isConnected = false; //断开后修改标识
				// this.reConnectWebSocket();
			};
			ws.onerror = (error) => {
				console.log('WebSocket出错', error);
				this.isConnected = false; //连接断开修改标识
				(this as any).reConnectWebSocket();
			};
			this.websocket = ws;
			this.websocketUrl = ws.url;
		},
	},
	persist: {
		// 持久化的值
		pick: ['imStore'],
	},
});

// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
	hot.accept(acceptHMRUpdate(useWebsocketStore, hot));
}
